import json
from django.db import models
from unitool.redis_model import ListModel, SortedSetModel

# Create your models here.

class IpProxyModel(ListModel):
    def __init__(self, *args, **kwargs):
        super().__init__(pkey='unitool_ip_proxy_list', *args, **kwargs)

    def search(self, data):
        '''
        @ 查找指定的元素 
        return 元素 index。 如果没有找到该元素则返回None
        '''
        for i in range(self.length()):
            redis_datas = self.index(i)
            if redis_datas.get('ip') == data.get('ip'):
                return i
        return -1
    
    def lpush(self, *values):
        for value in values:
            index = self.search(value)
            if index >=0:
                self.remove(self.index(index))
        return super().lpush(*values)

    def index(self, index):
        data = super().index(index)
        if isinstance(data, dict):
            return data
        if isinstance(data, bytes):
            data = data.decode()
        return json.loads(data.replace("'", '"'))
